//
//  DataViewController.m
//  ebook
//
//  Created by 吴超飞 on 16/1/15.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "DataViewController.h"
#import "UIImage+extension.h"
#import "AppDelegate.h"
#import "WebViewController.h"
#import "UIImage+RTTint.h"
#import "PageView.h"
#import "PageErrorView.h"
#import "ALBatteryView.h"
#import "ReaderGlobalModel.h"
#import "PCReaderTool.h"
#import "DownloadManager.h"

@interface DataViewController ()

@property (nonatomic, retain) PCReaderTool *readerTool;

@property (retain, nonatomic) UILabel *chapterLabel;
@property (retain, nonatomic) PageView *pageView;
@property (retain, nonatomic) UILabel *progressLabel;
@property (retain, nonatomic) UILabel *timeLabel;
@property (retain, nonatomic) ALBatteryView *batteryView;

@property (copy,   nonatomic) NSString *chapterName;

@end

@implementation DataViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];

    self.view.backgroundColor = [self getBgcolor];
    self.view.superview.backgroundColor = [self getBgcolor];
    
    [self.view addSubview:self.chapterLabel];
    [self.view addSubview:self.pageView];
    [self.view addSubview:self.progressLabel];
    [self.view addSubview:self.timeLabel];
    [self.view addSubview:self.batteryView];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"|-%d-[_pageView]-%d-|",[ReaderGlobalModel shareModel].readerConfig.padingLeft,[ReaderGlobalModel shareModel].readerConfig.padingRight] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_pageView)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-%d-[_pageView]-%d-|",[ReaderGlobalModel shareModel].readerConfig.padingTop,[ReaderGlobalModel shareModel].readerConfig.padingBottom] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_pageView)]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBgColor:) name:kChangePageColorNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.chapterName=self.chapter.chaptername;
    [self.chapterLabel setText:self.chapterName];
   
    [self setContent];
    [self.progressLabel setText:[NSString stringWithFormat:@"%ld/%ld", (long)self.currentPage + 1, (long)self.totalPage]];
    
    __weak typeof(self) weakSelf = self;
    [self.readerTool startMonitorTimeWithBlock:^(NSDate *currentDate) {
        __strong __typeof(self) strongSelf = weakSelf;
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        NSString *datestr = [dateFormatter stringFromDate:currentDate];
        strongSelf.timeLabel.text = datestr;
    }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.readerTool stopMonitorTime];
}

//设置内容
-(void)setContent{
    
    if([[DownloadManager shareInstance] isErrorContent:self.dataObject]){//未取到服务端的内容或网络错误
        PageErrorView *errorView = [[PageErrorView alloc] initWithFrame:self.view.bounds];
        [errorView setChapter:_chapter];
        [errorView setErrorInfo:self.dataObject];
        [self.view addSubview:errorView];
    }else{
        [self setAttributedText];
    }
}

-(UIColor *)getBgcolor{
    
    return [ReaderGlobalModel shareModel].readerConfig.ViewBgColor;
}

/*设置内容
 *第一段的段落样式要单独处理，根据是否独立段落还是承接上页，判断是否缩进
 */
-(void)setAttributedText{
    
    NSMutableDictionary *attributes = [[ReaderGlobalModel shareModel].attributes mutableCopy];
    [attributes removeObjectsForKeys:@[NSParagraphStyleAttributeName]];
    
    NSString *text = self.dataObject;
    if(!text)text=kInfoBlankText;
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
    int start = [text hasPrefix:@"\0"]?0:1;
    NSMutableAttributedString *attrText2 = [attrText mutableCopy];
    [attrText2 addAttribute:NSParagraphStyleAttributeName value:[ReaderGlobalModel shareModel].paragraphStyle range:NSMakeRange(start, [text length]-start)];
    if(attrText2)attrText=attrText2;
        
    [self.pageView setAttributedText:attrText];
    [self.pageView setNeedsDisplay];//解决scroll翻页有时候会出现空白的问题
}

- (void)setChapterName:(NSString *)chapterName {

    NSString *leftLines = @"—";
    CGSize singleLienSize = [leftLines sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}];
    NSMutableString *lines = [NSMutableString string];
    //没有括号死循环
    for (int i = 0; i < (MTScreenW/singleLienSize.width); i++) {
        [lines appendString:leftLines];
    }
    _chapterName = [NSString stringWithFormat:@"%@ %@ %@", leftLines, _chapter.chaptername, lines];
}

-(void)updateBgColor:(NSNotification *)noti{
    
    self.view.backgroundColor = [self getBgcolor];
    [self setContent];
    
    UIColor *chapterColor = [ReaderGlobalModel shareModel].readerConfig.TitleTextColor;
    self.chapterLabel.textColor = chapterColor;
    self.timeLabel.textColor = chapterColor;
    self.progressLabel.textColor = chapterColor;
    self.batteryView.batteryFill.backgroundColor = chapterColor;
}

#pragma mark - lazy loading

- (UILabel *)chapterLabel{
    
    if (!_chapterLabel) {
        float x = 15+LeftSpace;
        _chapterLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, 10 + TopSpace, MTScreenW - 2*x, 20)];
        _chapterLabel.textColor = [ReaderGlobalModel shareModel].readerConfig.TitleTextColor;
        _chapterLabel.font = [UIFont systemFontOfSize:13];
        _chapterLabel.textAlignment = NSTextAlignmentJustified;
        _chapterLabel.lineBreakMode = NSLineBreakByWordWrapping;
    }
    return _chapterLabel;
}

- (NSAttributedString *)getAttributeText:(NSString *)text textColor:(UIColor *)color{
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:text];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSForegroundColorAttributeName value:color range:strRange];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14.0] range:strRange];
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    return str;
}

- (PageView *)pageView
{
    if (!_pageView) {
        _pageView = [[PageView alloc] init];
        _pageView.translatesAutoresizingMaskIntoConstraints = NO;
        _pageView.backgroundColor = [UIColor clearColor];
    }
    return _pageView;
}

-(ALBatteryView *)batteryView
{
    
    if (!_batteryView) {
        _batteryView = [[ALBatteryView alloc] initWithFrame:CGRectMake([ReaderGlobalModel shareModel].readerConfig.padingLeft+LeftSpace, MTScreenH-22-TopSpace, 20, 20)];
    }
    [_batteryView setBatteryLevelWithColor:[ReaderGlobalModel shareModel].readerConfig.TitleTextColor forValue:[UIDevice currentDevice].batteryLevelInPercentage image:[ReaderGlobalModel shareModel].readerConfig.batteryImage];
    _batteryView.batteryFill.backgroundColor = [ReaderGlobalModel shareModel].readerConfig.TitleTextColor;
    return _batteryView;
}

- (UILabel *)progressLabel
{
    
    if (!_progressLabel) {
        _progressLabel = [[UILabel alloc] initWithFrame:CGRectMake(MTScreenW - 100 - [ReaderGlobalModel shareModel].readerConfig.padingRight-RightSpace, MTScreenH-22-TopSpace, 100, 20)];
        _progressLabel.font = [UIFont systemFontOfSize:12];
        _progressLabel.textColor = [ReaderGlobalModel shareModel].readerConfig.TitleTextColor;
        _progressLabel.textAlignment = NSTextAlignmentRight;
    }
    return _progressLabel;
}

- (UILabel *)timeLabel
{
    
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(40+LeftSpace, MTScreenH-22-TopSpace, 100, 20)];
        _timeLabel.font = [UIFont systemFontOfSize:12];
        _timeLabel.textColor = [ReaderGlobalModel shareModel].readerConfig.TitleTextColor;
    }
    return _timeLabel;
}

- (PCReaderTool *)readerTool
{
    if (!_readerTool) {
        _readerTool = [[PCReaderTool alloc] init];
    }
    return _readerTool;
}

-(void)dealloc{

    _dataObject = nil;
    _chapterName = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
}

@end

//@interface BackViewController ()
//
//@end
//
//@implementation BackViewController
//
//- (void)viewDidLoad {
//
//    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor clearColor];
//
//    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
//    [imageView setAutoresizingMask:UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth];
//    [imageView setImage:[ReaderGlobalModel shareModel].readerConfig.simuBackgroudImage];
//
//    BOOL isNight = [ReaderGlobalModel shareModel].readerConfig.IsNight;
//    [imageView setAlpha:isNight?0.3:0.75];
//
//    [self.view addSubview:imageView];
//}
//
//@end

@interface BackViewController ()
@property (nonatomic, strong) UIImage *backgroundImage;
@end

@implementation BackViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [imageView setAutoresizingMask:UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth];
    [imageView setImage:_backgroundImage];
    [imageView setAlpha:0.95];
    [self.view addSubview:imageView];
}

- (void)updateWithViewController:(UIViewController *)viewController {
    
    self.backgroundImage = [self captureView:viewController.view];
}

- (UIImage *)captureView:(UIView *)view {
    CGRect rect = view.bounds;
    UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGAffineTransform transform = CGAffineTransformMake(-1.0, 0.0, 0.0, 1.0, rect.size.width, 0.0);
    CGContextConcatCTM(context,transform);
    [view.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end
